package com.api.workflow.web;

import com.api.workflow.util.YNHttpUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * MMI004 供应商主数据接口
 * */
public class YNMMI004Action extends BaseBean implements Action {


    @Override
    public String execute(RequestInfo requestInfo) {
        String requestid = requestInfo.getRequestid();
        int formid = requestInfo.getRequestManager().getFormid();
        int formidAbs = Math.abs(formid);
        String tableName = "formtable_main_" + formidAbs;
        // 主表数据
        MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
        Property[] property = mainTableInfo.getProperty();
        Map<String, Object> mainTableInfoMap = new HashMap<>();
        for (int i = 0; i < property.length; i++) {
            String name = property[i].getName().toLowerCase();
            mainTableInfoMap.put(name, Util.null2String(property[i].getValue()));
        }
        writeLog("MMI001=======mainTableInfoMap:" + com.alibaba.fastjson.JSONObject.toJSONString(mainTableInfoMap));

        //明细表数据
        List<Map<String, Object>> detailTableMap = getMaps(requestInfo);
        writeLog("=============detailTableMap:" + com.alibaba.fastjson.JSONObject.toJSONString(detailTableMap));

        //业务逻辑
        try {
            //主表数据
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("BU_GROUP", mainTableInfoMap.get("ywhbfz"));
            jsonObject.put("NAME1", mainTableInfoMap.get("ywhbmc1"));
            jsonObject.put("BU_SORT1", mainTableInfoMap.get("jc"));
            jsonObject.put("BU_SORT2", mainTableInfoMap.get("jc"));
            jsonObject.put("TAXNUM", mainTableInfoMap.get("tyshxydm"));
            jsonObject.put("TAXTYPE", mainTableInfoMap.get("nslb"));
            jsonObject.put("VBUND", mainTableInfoMap.get("myhbbh"));
            jsonObject.put("ZXGLX", String.valueOf(mainTableInfoMap.get("czlx")));
            String czlx = mainTableInfoMap.get("czlx").toString();
            if (czlx.equals("C")) {
                if (String.valueOf(mainTableInfoMap.get("ywhbfz")).equals("Z006")) {
                    jsonObject.put("ZOABPID", mainTableInfoMap.get("gysbm"));
                } else {
                    jsonObject.put("ZOABPID", mainTableInfoMap.get("lcbh"));
                }
            } else {
                jsonObject.put("ZOABPID", mainTableInfoMap.get("gysbm"));
//                if (StringUtil.isNullOrEmpty(String.valueOf(mainTableInfoMap.get("gysxglch")))) {
//                    jsonObject.put("ZOABPID", mainTableInfoMap.get("gysbm"));
//                } else {
//                    jsonObject.put("ZOABPID", mainTableInfoMap.get("gysxglch"));
//                }
            }

            //明细1 银行信息
            JSONArray bank = new JSONArray();
            //明细2 采购
            JSONArray purchase = new JSONArray();
            //明细3 公司
            JSONArray company = new JSONArray();
            //明细4 地址
            JSONArray address = new JSONArray();
            for (int i = 0; i < detailTableMap.size(); i++) {
                Map<String, Object> map = detailTableMap.get(i);
                String tableDBName = map.get("tableDBName").toString();
                String substring = tableDBName.substring(tableDBName.length() - 3);
                if (substring.equals("dt1")) {
                    JSONObject bankInfo = new JSONObject();
                    bankInfo.put("BANKS", map.get("yxszgj"));
                    bankInfo.put("BANKL", map.get("yxlxh"));
                    bankInfo.put("BANKN", map.get("yxzh"));
                    bankInfo.put("KOINH", map.get("zhcyr"));
                    bankInfo.put("ACCNAME", map.get("zhmc"));
                    bankInfo.put("BKEXT", map.get("ckmx"));
                    //bankInfo.put("BKONT",map.get("ckmx"));

                    bank.add(bankInfo);
                }

                if (substring.equals("dt2")) {
                    JSONObject purchaseInfo = new JSONObject();
                    purchaseInfo.put("EKORG", map.get("cgzz"));
                    purchaseInfo.put("WEBRE", map.get("jyshdfpxy"));
                    purchaseInfo.put("WAERS", map.get("ddhb"));
                    purchaseInfo.put("SPERM", map.get("sxcgzzdj"));
                    purchaseInfo.put("KALSK", map.get("fazgys"));
                    purchaseInfo.put("ZTERM", map.get("fktj"));

                    purchase.add(purchaseInfo);
                }
                if (substring.equals("dt3")) {
                    JSONObject comInfo = new JSONObject();
                    comInfo.put("BUKRS", map.get("gsdm"));
                    comInfo.put("AKONT", map.get("dzkm"));
                    comInfo.put("ZWELS", map.get("fkfs"));
                    comInfo.put("SPERR", map.get("gzdjsygsdm"));

                    company.add(comInfo);
                }

                if (substring.equals("dt4")) {
                    JSONObject addInfo = new JSONObject();
                    addInfo.put("ADR_KIND", map.get("dzlx"));
                    addInfo.put("PSTLZ", map.get("yzxx"));
                    addInfo.put("LAND1", map.get("gjdqdm"));
                    String dq = String.valueOf(map.get("dq"));
                    RecordSet recordSet = new RecordSet();
                    recordSet.executeQuery("select bm from uf_dqsf where id=?", dq);
                    recordSet.next();
                    String bm = Util.null2String(recordSet.getString("bm"));
                    addInfo.put("REGIO", bm);
                    addInfo.put("ORT01", map.get("cs"));
                    addInfo.put("STREET", map.get("jd"));
                    addInfo.put("LANGU", map.get("yydm"));
                    addInfo.put("NAME_CO", map.get("dsrxm"));
                    addInfo.put("TELF1", map.get("dygdhhmqhhm"));
                    addInfo.put("TELF2", map.get("qdhjzdhhm"));
                    addInfo.put("TELFX", map.get("dygczhqhbh"));
                    addInfo.put("SMTP_ADDR", map.get("dzyjdz"));
                    address.add(addInfo);
                }
                jsonObject.put("BANKT", bank);
                jsonObject.put("LFM1T", purchase);
                jsonObject.put("LFB1T", company);
                jsonObject.put("ADRCT", address);

            }
            writeLog("MMI004=======jsonObject:" + jsonObject.toString());
            String post = YNHttpUtils.MMI004(jsonObject.toString(), YNHttpUtils.token());
            writeLog("MMI004=======post:" + post);

            RecordSet recordSet = new RecordSet();
            String updateMainTableName = "update " + tableName + " set  qqcsx = ? , fhjgx = ?  where  requestid = ? ";
            recordSet.executeUpdate(updateMainTableName, jsonObject.toString(), post, requestid);


            JSONObject jsonPOST = JSONObject.parseObject(post);
            String STATUS = jsonPOST.getString("STATUS");
            String MESSAGE = jsonPOST.getString("MESSAGE");

            if (!"S".equals(STATUS)) {

                requestInfo.getRequestManager()
                        .setMessageid(requestInfo.getRequestid() + "MMI004");
                requestInfo.getRequestManager().setMessagecontent("SAP接口异常，请联系SAP人员，错误信息提示::" + MESSAGE);
                return Action.FAILURE_AND_CONTINUE;

            }
            String PARTNER = jsonPOST.getString("PARTNER");
            String update = "update " + tableName + " set gysbm=?  where  requestid = ? ";
            if (czlx.equals("C")) {
                recordSet.executeUpdate(update, PARTNER, requestid);
            }


        } catch (Exception e) {
            e.printStackTrace();
            requestInfo.getRequestManager()
                    .setMessageid(requestInfo.getRequestid() + "MMI004");
            requestInfo.getRequestManager().setMessagecontent("接口异常:" + e.toString());
            return Action.FAILURE_AND_CONTINUE;

        }


        return Action.SUCCESS;

    }


    /**
     * 提取明细表全部的数据
     *
     * @param requestInfo
     * @return
     */
    private static List<Map<String, Object>> getMaps(RequestInfo requestInfo) {
        DetailTable[] detailTable = requestInfo.getDetailTableInfo().getDetailTable();
        //这里是存储了全部的明细表数据  可自行修改存储结构
        List<Map<String, Object>> detailTableMap = new ArrayList<>();
        if (detailTable.length > 0) {
            for (int i = 0; i < detailTable.length; i++) {
                DetailTable dt = detailTable[i];
                Row[] s = dt.getRow();
                for (int j = 0; j < s.length; j++) {
                    Row r = s[j];
                    Cell c[] = r.getCell();
                    Map<String, Object> objectObjectHashMap = new HashMap<>();
                    for (int k = 0; k < c.length; k++) {
                        Cell c1 = c[k];
                        String name = c1.getName().toLowerCase();
                        String value = c1.getValue();
                        objectObjectHashMap.put(name, value);
                    }
                    objectObjectHashMap.put("tableDBName", dt.getTableDBName());
                    detailTableMap.add(objectObjectHashMap);
                }
            }
        }
        return detailTableMap;
    }

}
